package com.theatre.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theatre.userservice.mapper.CartMapper;
import com.theatre.userservice.model.entity.Cart;
import com.theatre.userservice.model.entity.Script;
import com.theatre.userservice.model.vo.CartVO;
import com.theatre.userservice.model.vo.PublisherVO;
import com.theatre.userservice.model.vo.ScriptVO;
import com.theatre.userservice.service.CartService;
import com.theatre.userservice.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ScriptService scriptService; // 用于后续结算时修改剧本状态

    /**
     * 添加到购物车
     */
    @Override
    public boolean addToCart(Cart cart) {
        // 判断是否已存在相同剧本
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getShopId, cart.getShopId())
                .eq(Cart::getScriptId, cart.getScriptId());
        Cart existing = cartMapper.selectOne(wrapper);
        if (existing != null) {
            throw new IllegalArgumentException("已存在相同剧本");
            // 已经存在则不重复添加
        }
        return cartMapper.insert(cart) > 0;
    }

    /**
     * 删除购物车中的某项
     */
    @Override
    public boolean removeFromCart(Long id) {
        return cartMapper.deleteById(id) > 0;
    }

    /**
     * 查看当前商铺的购物车
     */
    @Override
    public List<CartVO> listCartByShopId(Long shopId) {
        // 查询该商铺的购物车记录
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getShopId, shopId);
        List<Cart> cartList = cartMapper.selectList(wrapper);

        if (cartList.isEmpty()) return List.of();

        // 构建返回结果
        List<CartVO> result = new ArrayList<>();

        for (Cart cart : cartList) {
            // 查询剧本信息
            Script script = scriptService.getById(cart.getScriptId());
            if (script == null) continue;

            // 组装 ScriptVO
            ScriptVO scriptVO = new ScriptVO();
            scriptVO.setId(script.getId());
            scriptVO.setTitle(script.getTitle());
            scriptVO.setAuthor(script.getAuthor());
            scriptVO.setContentFile(script.getContentFile());
            scriptVO.setCategoryId(script.getCategoryId());
            scriptVO.setPrice(script.getPrice());
            scriptVO.setPublisherName(script.getPublishName()) ;

            // 组装 CartVO
            CartVO cartVO = new CartVO();
            cartVO.setId(cart.getId());
            cartVO.setShopId(cart.getShopId());
            cartVO.setScriptVO(scriptVO);

            result.add(cartVO);
        }

        return result;
    }


    /**
     * 清空购物车
     */
    @Override
    public boolean clearCart(Long shopId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getShopId, shopId);
        return cartMapper.delete(wrapper) > 0;
    }

    /**
     * 结算（购买）
     * 1. 查询当前购物车的所有剧本
     * 2. 标记剧本为“已售出”
     * 3. 更新剧本的“商铺”和“过期时间”
     * 4. 清空购物车
     */
    @Transactional
    @Override
    public BigDecimal checkout(Long shopId) {
        List<CartVO> cartList = listCartByShopId(shopId);
        if (cartList.isEmpty()) return BigDecimal.ZERO;

        BigDecimal totalPrice = BigDecimal.ZERO;


        // 更新剧本状态
        for (CartVO cartVO : cartList) {
            Script script = scriptService.getById(cartVO.getScriptVO().getId());
            if (script == null) continue;

            // 累加价格（如果价格为null则跳过）
            if (script.getPrice() != null) {
                totalPrice = totalPrice.add(script.getPrice());
            }

            // 使用期限天数（如果没设置，默认 30 天）
            Integer usageDays = script.getUsageDays() != null ? script.getUsageDays() : 30;

            // 计算到期时间
            LocalDateTime expireTime = LocalDateTime.now().plusDays(usageDays);

            scriptService.update()
                    .eq("id", script.getId())
                    .set("sold", 1)                  // 已售出
                    .set("shop_id", shopId)          // 归属店铺
                    .set("expire_time", expireTime)  // 到期时间
                    .update();
        }
        // 清空购物车
        clearCart(shopId);
        return totalPrice;
    }
}
